<script setup lang="ts">
import { addPark, editPark, getIndustryList, getParkDetail } from "@/api/park";
import { uploadFile } from "@/api/upload";
import type { AddPark, IndustryList } from "@/types/park";
import {
  ElMessage,
  ElMessageBox,
  type FormInstance,
  type FormRules,
  type UploadRequestOptions,
  type UploadUserFile,
} from "element-plus";
// import type { FormRules } from "element-plus/lib/components/index.js";
import { onMounted, ref } from "vue";
import { useRoute, useRouter } from "vue-router";

// 根据接口文档定义字段，用于表单双向绑定
const addForm = ref<AddPark>({
  name: "", // 企业名称
  legalPerson: "", // 法人
  registeredAddress: "", // 注册地址
  industryCode: null, // 所在行业
  contact: "", // 企业联系人
  contactNumber: "", // 联系人电话
  businessLicenseUrl: "", // 营业执照url
  businessLicenseId: null, // 营业执照id
  id:undefined
});
const addParkRef = ref<FormInstance>();
const rules = ref<FormRules<AddPark>>({
  name: [{ required: true, message: "请输入企业名称", trigger: "blur" }],
  legalPerson: [{ required: true, message: "请输入法人", trigger: "blur" }],
  registeredAddress: [
    { required: true, message: "请输入注册地址", trigger: "blur" },
  ],
  industryCode: [{ required: true, message: "请选择行业", trigger: "change" }],
  contact: [{ required: true, message: "请输入企业联系人", trigger: "blur" }],
  contactNumber: [
    { required: true, message: "请输入联系电话", trigger: "blur" },
  ],
  businessLicenseUrl: [
    { required: true, message: "请上传营业执照", trigger: "change" },
  ],
});
const IndustryData = ref<IndustryList[]>([]);
const getIndustry = async () => {
  const res = await getIndustryList();
  IndustryData.value = res.data;
};
// 查看企业详情
const Detail=async(id:number)=>{
  const res=await getParkDetail(id.toString())
  addForm.value.name=res.data.name
  addForm.value.legalPerson=res.data.legalPerson
  addForm.value.registeredAddress=res.data.registeredAddress
  addForm.value.industryCode=res.data.industryCode
  addForm.value.contact=res.data.contact
  addForm.value.contactNumber=res.data.contactNumber
  addForm.value.businessLicenseUrl=res.data.businessLicenseUrl
  addForm.value.businessLicenseId=res.data.businessLicenseId

  fileList.value=[{
  name:res.data.name,
  url:res.data.businessLicenseUrl
 }]
}
// const editPrise=async()=>{
//   await editPark(addForm.value)
// }
const route=useRoute()
onMounted(() => {
  getIndustry();
  if(route.params.id){
    const ids=Number(route.params.id)
    Detail(ids)
    addForm.value.id=ids
  }
});
// 上传营业执照
const fileList = ref<UploadUserFile[]>([]);
const UploadFile = async (obj: UploadRequestOptions) => {
  const fd = new FormData();
  fd.append("file", obj.file);
  fd.append("type", "businessLicense");
  const res = await uploadFile(fd);
  addForm.value.businessLicenseUrl = res.data.url;
  addForm.value.businessLicenseId = res.data.id;
  addParkRef.value?.validateField("businessLicenseUrl");
};
// 对文件大小判断
const beforeUpload = (file: File) => {
  console.log("file", file);
  const filetype = file.name.split(".");
  if (filetype[1] === "jpg" || filetype[1] === "png") {
    if (file.size <= 500 * 1024) {
      ElMessage.success("上传成功");
      return true;
    } else {
      ElMessage.error("上传文件过大");
      return false;
    }
  } else {
    ElMessage.error("上传文件类型错误");
    return false;
  }
};
// 清除文件
const DelFile = () => {
  fileList.value = [];
  addForm.value.businessLicenseUrl = "";
  addForm.value.businessLicenseId = null;
  addParkRef.value?.validateField("businessLicenseUrl");
};
const router = useRouter();
const loading = ref(false);
// 提交表单
const submitForm = async () => {
  try {
    await addParkRef.value?.validate();
    loading.value = true;
    if(route.params.id){
     const res= await editPark(addForm.value)
     console.log('res',res);
      if (res.code === 10000) {
      ElMessage.success("编辑成功");
      router.back();
      loading.value = false;
    }
    }else{
      const res = await addPark(addForm.value);
    // console.log("res", res);
    if (res.code === 10000) {
      ElMessage.success("添加成功");
      router.back();
      loading.value = false;
    }
    }

  } catch {}
};
// 重置表单
const clearForm = () => {
  ElMessageBox.confirm("确定要重置表单吗?", "提示一下", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(() => {
      addParkRef.value?.resetFields();
      DelFile();
      ElMessage({
        type: "success",
        message: "已重置",
      });
    })
    .catch(() => {
      ElMessage({
        type: "info",
        message: "取消操作",
      });
    });
};
</script>

<template>
  <div class="add-enterprise">
    <header class="add-header">
      <el-page-header v-if="$route.params.id" content="编辑企业" @back="$router.back()" />
      <el-page-header v-else content="添加企业" @back="$router.back()" />
    </header>
    <main class="add-main">
      <div class="form-container">
        <div class="title">企业信息</div>
        {{ addForm }}
        <div class="form">
          <el-form
            ref="addParkRef"
            label-width="100px"
            :model="addForm"
            :rules="rules"
          >
            <el-form-item label="企业名称" prop="name">
              <el-input v-model="addForm.name" />
            </el-form-item>
            <el-form-item label="法人" prop="legalPerson">
              <el-input v-model="addForm.legalPerson" />
            </el-form-item>
            <el-form-item label="注册地址" prop="registeredAddress">
              <el-input v-model="addForm.registeredAddress" />
            </el-form-item>
            <el-form-item label="所在行业" prop="industryCode">
              <el-select v-model="addForm.industryCode as number">
                <el-option
                  v-for="item in IndustryData"
                  :key="item.industryCode"
                  :label="item.industryName"
                  :value="item.industryCode"
                />
              </el-select>
            </el-form-item>
            <el-form-item label="企业联系人" prop="contact">
              <el-input v-model="addForm.contact" />
            </el-form-item>
            <el-form-item label="联系电话" prop="contactNumber">
              <el-input v-model="addForm.contactNumber" />
            </el-form-item>
            <el-form-item label="营业执照" prop="businessLicenseUrl">
              <el-upload
                v-model:file-list="fileList"
                class="upload-demo"
                :http-request="UploadFile"
                :before-upload="beforeUpload"
                :on-remove="DelFile"
                :limit="1"
              >
                <el-button type="primary">Click to upload</el-button>
                <template #tip>
                  <!-- 用于显示上传文件信息 -->
                  <div class="el-upload__tip">
                    jpg/png files with a size less than 500KB.
                  </div>
                </template>
              </el-upload>
            </el-form-item>
          </el-form>
        </div>
      </div>
    </main>
    <footer class="add-footer">
      <div class="btn-container">
        <el-button @click="clearForm">重置</el-button>
        <el-button type="primary" @click="submitForm">{{loading?'加载中':'提交'}}</el-button>
      </div>
    </footer>
  </div>
</template>

<style scoped lang="scss">
.add-enterprise {
  background-color: #f4f6f8;
  height: 100vh;

  .add-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 0 20px;
    height: 64px;
    line-height: 64px;
    font-size: 16px;
    font-weight: bold;
    background-color: #fff;

    .left {
      span {
        margin-right: 4px;
      }

      .arrow {
        cursor: pointer;
      }
    }

    .right {
      text-align: right;
    }
  }

  .add-main {
    background: #f4f6f8;
    padding: 20px 130px;

    .form-container {
      background-color: #fff;

      .title {
        height: 60px;
        line-height: 60px;
        padding-left: 20px;
      }

      .form {
        margin-bottom: 20px;
        padding: 20px 65px 24px;

        .el-form {
          display: flex;
          flex-wrap: wrap;

          .el-form-item {
            width: 50%;
          }
        }
      }
    }
  }

  .add-footer {
    position: fixed;
    bottom: 0;
    width: 100%;
    padding: 24px 50px;
    color: #000000d9;
    font-size: 14px;
    background: #fff;
    text-align: center;
  }
}
</style>
